package sk.tuke.android4all.dialer;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnGenericMotionListener;
import android.view.ViewGroup;
import android.widget.TextView;
import sk.tuke.android4all.controls.CustomFragment;
import sk.tuke.android4all.listeners.SwipeListener;
import sk.tuke.android4all.services.Tts;

public class DialerFragment extends CustomFragment {

	private static String TAG = "Dialer";
	private Activity mActivity = null;
	private String selectedTag = null;
	int touchCounter = 0;
	private final int TOUCH_INTENSITY = 4;
	private SwipeListener mActionListener = null;
	private Tts mSpeechEngine;
	private StringBuilder mNumberBuffer = null;
	
	public DialerFragment(Activity aActivity_in){
		mActivity = aActivity_in;
		selectedTag = "";
		mSpeechEngine = new Tts(mActivity);
		mNumberBuffer = new StringBuilder();
	}
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_dialer, container, false);	       
        return rootView;
    }
	
	@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        createUI();
    }
	
	private void createUI() {
		mActionListener =  new SwipeListener(mActivity) {
            @Override
            public void onDoubleTapAction(int count) {
                Log.i("TAG", "DoubleTapped " + selectedTag);
                resetTouchCounter();
                if(selectedTag != null){
                	if(selectedTag == getResources().getString(R.string.fragmentdialer_contacts)){
                		mSpeechEngine.sayMessage("Contacts");
                		mActivity.getFragmentManager().beginTransaction().replace(R.id.container, new ContactsFragment(mActivity), ContactsFragment.class.getName()).commit();
                	}else if (selectedTag == getResources().getString(R.string.fragmentdialer_history)){	
                		mSpeechEngine.sayMessage("History");
                		mActivity.getFragmentManager().beginTransaction().replace(R.id.container, new HistoryFragment(mActivity), HistoryFragment.class.getName()).commit();
                	}else if(selectedTag == getResources().getString(R.string.fragmentdialer_back)){
                		mSpeechEngine.sayMessage(selectedTag);
                		if(mNumberBuffer.length()>0){
                			mNumberBuffer.deleteCharAt(mNumberBuffer.length() -1);
                			((TextView)getView().findViewById(R.id.fragmentdialer_number)).setText(mNumberBuffer.toString());
                		}
                	}else if(selectedTag == getResources().getString(R.string.fragmentdialer_call)){
                		mSpeechEngine.sayMessage(getResources().getString(R.string.fragmentdialer_calling));
                		String callingNumber = "tel:" + mNumberBuffer.toString();
                		Intent intent = new Intent(Intent.ACTION_CALL);
                		intent.setData(Uri.parse(callingNumber));
                		startActivity(intent);
                	}else if(selectedTag =="number"){}
                	else{
                		mSpeechEngine.sayMessage(selectedTag);
                		mNumberBuffer.append(selectedTag);
                		((TextView)getView().findViewById(R.id.fragmentdialer_number)).setText(mNumberBuffer.toString());
                	}
                }
            }

			@Override
			public void onZoomInAction() {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onZoomOutAction() {
				// TODO Auto-generated method stub
				
			}
		};
		getView().setOnTouchListener(mActionListener);
		
		setNumbers();
		setNavigationControls();
		setDisplayedNumber();
	}
	
	private void setNavigationControls() {
		//TextView historyButton = (TextView) getView().findViewById(R.id.fragmentdialer_history);
		//TextView contactsButton = (TextView) getView().findViewById(R.id.fragmentdialer_contacts);
		
		setDigitControl(R.id.fragmentdialer_contacts);
		setDigitControl(R.id.fragmentdialer_history);
		setDigitControl(R.id.fragmentdialer_call);
		setDigitControl(R.id.fragmentdialer_back);
	}

	private void setNumbers(){
		setDigitControl(R.id.fragmentdialer_one);
		setDigitControl(R.id.fragmentdialer_two);
		setDigitControl(R.id.fragmentdialer_three);
		setDigitControl(R.id.fragmentdialer_four);
		setDigitControl(R.id.fragmentdialer_five);
		setDigitControl(R.id.fragmentdialer_six);
		setDigitControl(R.id.fragmentdialer_seven);
		setDigitControl(R.id.fragmentdialer_eight);
		setDigitControl(R.id.fragmentdialer_nine);
		setDigitControl(R.id.fragmentdialer_asterisc);
		setDigitControl(R.id.fragmentdialer_zero);
		setDigitControl(R.id.fragmentdialer_plus);
	}
            
	private void setDigitControl(int controlId){
		final TextView controlTv = (TextView) getView().findViewById(controlId);
		controlTv.setOnGenericMotionListener(new OnGenericMotionListener(){

			@Override
			public boolean onGenericMotion(View arg0, MotionEvent arg1) {
				mActionListener.resetTouchCounter();
				String textInControl = controlTv.getText().toString();
                if (selectedTag != textInControl && touchCounter>TOUCH_INTENSITY) {
                    touchCounter = 0;
                    mSpeechEngine.sayMessage(textInControl);
                    selectedTag = controlTv.getText().toString();
                }else{
                    touchCounter++;
                }
                return false;
			}});
	}
	
	private void setDisplayedNumber(){
		final TextView aNumber_tv = (TextView)getView().findViewById(R.id.fragmentdialer_number);
		aNumber_tv.setText("");
		
		aNumber_tv.setOnGenericMotionListener(new OnGenericMotionListener(){

			@Override
			public boolean onGenericMotion(View arg0, MotionEvent arg1) {
				mActionListener.resetTouchCounter();
				String textInControl = "number";
                if (selectedTag != textInControl && touchCounter>TOUCH_INTENSITY) {
                    touchCounter = 0;
                    for(int i = 0; i< mNumberBuffer.length(); i++){
                    	mSpeechEngine.sayMessage(String.valueOf(mNumberBuffer.charAt(i)));
                    	try{
                    		Thread.sleep(750);
                    	}catch(Exception ex){
                    		//Do nothing
                    	}
                    }
                    
                    selectedTag = textInControl;
                }else{
                    touchCounter++;
                }
				
				return false;
			}});
	}

	@Override
	public void returnAction() {
		mActivity.finish();
	}

}
